import 'dart:math';
import 'dart:ui';

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/home/alumb_vo_list.dart';
import 'package:qianyi/entity/home/trendVo.dart';
import 'package:qianyi/entity/user_entity.dart';
import 'package:qianyi/network/http_entity.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/pages/home/mine/mock.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/mine/user_view_model.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/tag.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:get/get.dart';
import 'package:shimmer_animation/shimmer_animation.dart';
import 'package:sliver_tools/sliver_tools.dart';

import '../../../controller/imageDetailVideoController.dart';
import '../../../entity/mine/User.dart';
import '../../../network/http_config.dart';
import '../../../network/http_manager.dart';
import '../../../state/token.dart';
import '../../../ui/sliverAppBar/animation/animation_enum.dart';
import '../../../ui/sliverAppBar/sliver_adsorption/sliver_adsorption_appbar.dart';
import '../../../ui/sliverAppBar/sliver_example.dart';
import '../../../ui/widget/custom_refresh.dart';
import '../../../view_model/mine/album_view_model.dart';
import '../../../view_model/mine/trend_view_user_model.dart';
import 'dongtai/collection_view_mine.dart';
import 'dongtai/PageViewMine.dart';
import 'dongtai/album_view_mine.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

class PageViewMine extends StatefulWidget {
  const PageViewMine({Key? key}) : super(key: key);

  @override
  State<PageViewMine> createState() => _PageViewMineState();
}

/// TODO: NestedScrollView 如何实现上拉加载，下拉刷新

class _PageViewMineState extends State<PageViewMine> with AutomaticKeepAliveClientMixin ,TickerProviderStateMixin {
  TokenController tokenController = Get.find();
  ScrollController controller = ScrollController();

  final List<String> tabs = ["动态", "专辑","收藏"];
  final PageController _pageController = PageController(initialPage: 1);
  bool isLoad = false;
  String avatar = '';
  @override
  void initState() {
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    // TODO: implement initState
    super.initState();
    watiUser();

  }
  watiUser() async{
    await tokenController.getUserInfo();

    setState(() {
      isLoad = true;
    });
  }
  @override
  Widget build(BuildContext context) {


    return !isLoad? Shimmer(
      duration: Duration(seconds: 3), //Default value
      interval: Duration(seconds: 5), //Default value: Duration(seconds: 0)
      color: Colors.grey, //Default value
      colorOpacity: 0.3, //Default value
      enabled: true, //Default value
      direction: ShimmerDirection.fromLTRB(),  //Default Value
      child: Container(
        color: Colors.white,
      ),
    ):DefaultTabController(
      length: tabs.length,
      child: SliverAdsorptionAppbar(

        animationEnum: AnimationEnum.upToDown,
        controller: controller,
        collapsedColors: Colors.white,
        collapsedHeight: 100,
        expandedHeight: 300,
        expandedWidget: Container(

          padding: const EdgeInsets.only(top: 10, left: 10, right: 10),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.grey[50]!,
                Colors.blue[50]!,
              ],
            ),
          ),
          // color: Colors.blueGrey.withOpacity(.03),
          child: Obx(()=>ListView(

            children: [


              ClipRRect(
                borderRadius: BorderRadius.circular(10), // 设置圆角的大小
                child: Container(
                  width: 70,
                  height: kIsWeb? 120:120,

                  child: FancyShimmerImage(
                    boxDecoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.white, // 设置边框颜色
                        width: 2, // 设置边框宽度
                      ),
                      borderRadius: BorderRadius.circular(10), // 设置圆角的大小，与ClipRRect的圆角大小保持一致
                    ),
                    imageUrl: "${tokenController.cover.value}",
                  ),
                ),
              )

              ,

              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(40),
                    child: FancyShimmerImage(
                      width: 70,
                      height: 70, imageUrl: "${tokenController.avatar.value}",
                    ),
                  )

                  ,
                  const SizedBox(width: 10),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "${tokenController.user!.value[0].username}",
                        style: TextStyle(fontSize: 18),
                      ),
                      SizedBox(height: 5),
                      Text(
                        "id号：${tokenController.user!.value[0].id?.substring(5,15).toString()}",
                        style: TextStyle(color: Colors.black45),
                      ),
                    ],
                  ),
                  const Spacer(),
                  GestureDetector(
                      onTap: (){
                        Get.toNamed("/user/editUser");
                      },
                      child: Column(
                        children: [
                          Icon(Icons.edit_calendar_outlined, color: Colors.black38),
                          Text(
                            "编辑",
                            style: TextStyle(color: Colors.black26, fontSize: 12),
                          ),
                        ],
                      )
                  )
                  ,
                ],
              ),


              Text(
                maxLines: 2, // 限制最多显示两行
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                "个性签名：${tokenController.user!.last.description == null?'还没有简介':tokenController.user!.last.description}",
                style: TextStyle(fontSize: 14, color: Colors.black38),
              ),


              // const SizedBox(height: 10),
              Row(
                children: [
                  GestureDetector(
                    child: Padding(padding: EdgeInsets.only(right: 10,top: 10,bottom: 10),child: Column(
                      children: [
                        Obx(()=>

                            Text('${tokenController.user!.last.followCount}'),

                        ),
                        Text('关注')
                      ],
                    )),
                    onTap: () {
                      Get.toNamed("/mine/firends");

                    },
                  ),
                  GestureDetector(
                    onTap: (){
                      Get.toNamed("/mine/fans");

                    },
                    child: Padding(padding: EdgeInsets.all(10),child: Column(
                      children: [
                        Obx(()=>

                            Text('${tokenController.user!.last.fanCount}'),

                        ),
                        Text('粉丝')
                      ],
                    )),
                  )

                  ,
                  Padding(padding: EdgeInsets.all(10),child: Column(
                    children: [
                      Obx(()=>

                          Text('${tokenController.user!.last.trendCount}'),

                      ),
                      Text('动态')
                    ],
                  ))

                ],
              ),

            ],
          )),

        ),

        collapsedWidget: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
          child: Row(
            children: [
              Column(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(40),
                    child: FancyShimmerImage(

                      width: 50,
                      height: 50, imageUrl: "${tokenController.avatar.value}",
                    ),
                  )
                ],
              )


              ,
              const SizedBox(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "${tokenController.user!.value[0].username}",
                    style: TextStyle(fontSize: 18),
                  ),
                  SizedBox(height: 5),
                  Text(
                    "id号：${tokenController.user!.value[0].id?.substring(5,15).toString()}",
                    style: TextStyle(color: Colors.black45),
                  ),
                ],
              ),
              const Spacer(),
              GestureDetector(
                  onTap: (){
                    Get.toNamed("/user/editUser");
                  },
                  child: Column(
                    children: [
                      Icon(Icons.edit_calendar_outlined, color: Colors.black38),
                      Text(
                        "编辑",
                        style: TextStyle(color: Colors.black26, fontSize: 12),
                      ),
                    ],
                  )
              )
              ,
            ],
          ),
        ),

        slivers: [
          SliverAppBar(
            primary: false,
            toolbarHeight: 0,
            pinned: true,
            // backgroundColor: Colors.transparent,
            bottom: TabBar(
              indicatorColor: WcaoTheme.primary,
              indicatorSize: TabBarIndicatorSize.tab,
              unselectedLabelColor: WcaoTheme.indexBootBarColor,
              unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),
              labelColor: WcaoTheme.indexBootBarActColor,
              labelStyle: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.symmetric(horizontal: 46),
              tabs: tabs
                  .map((e) => Tab(
                text: e,
              ))
                  .toList(),
            ),

          ),
          // SliverList(
          //   delegate: SliverChildBuilderDelegate(
          //         (c, i) {
          //       return Container(
          //         margin: const EdgeInsets.only(bottom: 10),
          //         color: Colors.blue,
          //         height: 100,
          //         child: Center(
          //           child: Text(
          //             "$i",
          //             style: const TextStyle(color: Colors.white, fontSize: 20),
          //           ),
          //         ),
          //       );
          //     },
          //     childCount: 50,
          //   ),
          // ),

          // SliverFillRemaining(
          //   child:
          //   TabBarView(
          //     children: [
          //       TrendViewUserPage(),
          //       AlbumViewMine(),
          //       ColloectionMine(),
          //     ],
          //   ),
          // )
          //  SliverToBoxAdapter(
          //   child: Container(
          //     child: TabBarView(
          //       children: [
          //         TrendViewUserPage(),
          //         AlbumViewMine(),
          //         ColloectionMine(),
          //       ],
          //     ),
          //   ),
          // ),
        ],
        bodyT:
        TabBarView(
          children: [
            TrendViewUserPage(),
            AlbumViewMine(),
            ColloectionMine(),
          ],
        ),


      ),
    );




  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  double getRandomHeight() {
    // 生成一个随机高度
    double height = Random().nextDouble() * (230 - 80) + 138;
    return   height ;
  }
  buildWateFall(TrendViewUserModel viewModel) {
    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();
    return MasonryGridView.count(
      padding: EdgeInsets.all(2),
      // 展示几列
      crossAxisCount: 2,

      // 元素总个数
      itemCount: viewModel.datas.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) {
        TrendEntity trendEntity = viewModel.datas[index];
        // var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
        return GestureDetector(
          onTap: () async {
            HudUtil.showBeautiful(context);
            String uid = await tokenController.getUid();
            Map<String,dynamic> params = {
              "mid":trendEntity.mid,
              "uid": uid
            };
            await HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
            imageDetailVideoController.imageDetailId.value = trendEntity.mid!;
            await imageDetailVideoController.getImageVideoDetail();
            // Loader.hide();
            HudUtil.dismiss();
            Get.toNamed("/ui/home/imageVideoDetail");

          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child:  Column(
              children: [
                FancyShimmerImage(
                  height: getRandomHeight(),
                  imageUrl: trendEntity.cover!,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [

                    Flexible(

                      child: Text(
                        trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                        overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                      ),

                    ),
                    Row(
                      children: [
                        Icon(
                          CupertinoIcons.heart,size: 14,
                          color: Colors.grey,),
                        Text(trendEntity.agreeCount as String)
                      ],
                    )



                  ],
                )

                ,


              ],
            ),
          ),
        );
      },

      // 纵向元素间距
      mainAxisSpacing: 5,
      // 横向元素间距
      crossAxisSpacing: 5,
      //本身不滚动，让外面的singlescrollview来滚动
      physics:const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    )

    //   WaterfallFlow.builder(
    //   padding: EdgeInsets.all(8.0),
    //   gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
    //     crossAxisCount: 2,
    //
    //     crossAxisSpacing: 5.0,
    //     mainAxisSpacing: 5.0,
    //   ),
    //   itemCount: viewModel.datas.length,
    //   itemBuilder: (BuildContext context, int index) {
    //     TrendEntity trendEntity = viewModel.datas[index];
    //     var imgsUrl = jsonDecode(trendEntity.imgsUrl as String);
    //     double height = getRandomHeight();
    //     return Container(
    //       // color: Colors.blue,
    //       height: height,
    //       child: Center(
    //         child: FancyShimmerImage(
    //           height: height-30,
    //           imageUrl: imgsUrl[0],
    //         ),
    //       ),
    //     );
    //   },
    // )
        ;


  }

  Widget createAddAlbum() {
    return Container(
      width: 50,
      height: 30,
      child:  MaterialButton(

        //背景颜色
        color: WcaoTheme.primary,
        //边框样式
        shape: const RoundedRectangleBorder(
          //边框颜色
          side: BorderSide(
            color: Colors.deepPurple,
            width: 1,
          ),
          //边框圆角
          borderRadius: BorderRadius.all(
            Radius.circular(8),
          ),
        ),
        //按钮高度
        height: 32,
        //按钮最小宽度
        minWidth: 60,
        //点击事件
        onPressed: () {},
        child: const Text(
          "查找",
          style: TextStyle(fontSize: 12, color: Colors.deepPurple),
        ),
      ),
    )
    ;

  }
}
